import React, { useEffect } from 'react';
import ProLayout from '@ant-design/pro-layout';
import Link from 'umi/link';
import { connect } from 'dva';
import request from 'umi-request';
import _ from 'lodash';
import { VisualizerProvider } from 'react-lifecycle-visualizer';
import Authorized, { reloadAuthorized } from '@/utils/Authorized';
import { handlerMatomoEvent } from '@/utils/matomo';
import GlobalHeader from '@/components/GlobalHeader';
import { router } from 'umi';
import './BasicLayout.less';
import PageLoading from '@/components/PageLoading';

const BasicLayout = props => {
  const { dispatch, children, settings, orgStructure, configMenus, Permissions } = props;
  const { menus } = Permissions;
  // 获取用户信息、组织架构信息、字典信息
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
        payload: {
          callback: async data => {
            if (!_.isEmpty(data)) {
              await localStorage.setItem('userInit', JSON.stringify(data));
              await window._paq.push(['setUserId', `${data.usercn}_${data.mail}`]);
              // 业务系统接入“产品新功能弹窗公告服务

              if (!_.isEmpty(data.alias)) {
                const res = await request(`${process.env.iTopUrl}/api/popWindow/pop`, {
                  method: 'GET',
                  params: {
                    product_id: '5', // 业务系统在IT运营平台中的ID，***注***：测试与生产的id可能不一致
                    app_code: data.alias, // 当前登录用户的alias
                    terminal: '1', // 1表示pc端，2表示移动
                  },
                });
                if (res) {
                  const frag = document.createRange().createContextualFragment(res);
                  const body = document.querySelector('body');
                  body.appendChild(frag);
                }
              }
            }
          },
        },
      });
      dispatch({
        type: 'Permissions/fetch',
        payload: {
          callback: data => {
            if (_.isEmpty(data) || _.isEmpty(data.menus)) router.push('/403');
            reloadAuthorized();
          },
        },
      });
      dispatch({
        type: 'global/fetchAreaSegments',
      });
      dispatch({
        type: 'global/fetchProTypes',
      });
      dispatch({
        type: 'global/fetchProducts',
      });
      // 组织架构信息
      dispatch({
        type: 'orgStructure/fetch',
      });
      dispatch({
        type: 'settings/getSetting',
      });
      dispatch({
        type: 'global/fetchMenus',
      });
    }
  }, []);

  // 页面埋点
  const handlerMenuMatomo = menuItem => {
    const params = {
      category: 'Menu',
      action: menuItem.name,
      name: menuItem.name,
    };
    handlerMatomoEvent(params);
  };

  /**
   * init variables
   */
  const handleMenuCollapse = payload => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };

  const getMenus = item => {
    const list = [];
    item.forEach(element => {
      if (element.perType.toString() === '1') {
        list.push(element);
        if (element.childMenu && element.childMenu.length > 0) {
          list.push(...getMenus(element.childMenu));
        }
      }
    });
    return list;
  };
  /* 根据权限显示对应的左侧菜单 */
  const menuDataRender = menuList => {
    const flatConfigMenus = getMenus(configMenus);
    return menuList.map(item => {
      const flatConfigMenu = _.first(
        _.filter(flatConfigMenus, element => _.indexOf(item.authority, element.perCode) > -1),
      );
      const localItem = {
        ...item,
        size: 'large',
        name: flatConfigMenu ? flatConfigMenu.perName : item.name,
        children: item.children ? menuDataRender(item.children) : [],
      };
      return Authorized.check(item.authority, localItem, null);
    });
  };
  return (
    <VisualizerProvider>
      {_.isEmpty(menus) ? (
        <PageLoading />
      ) : (
        <ProLayout
          siderWidth="180"
          menuHeaderRender={() => (
            <div className="log-img" style={{ width: '100%', height: '100%' }} />
          )}
          headerRender={() => <GlobalHeader {...props} />}
          onCollapse={handleMenuCollapse}
          menuItemRender={(menuItemProps, defaultDom) => {
            if (menuItemProps.isUrl) {
              return defaultDom;
            }
            return (
              <Link to={menuItemProps.path} onClick={() => handlerMenuMatomo(menuItemProps)}>
                {defaultDom}
              </Link>
            );
          }}
          menuDataRender={menuDataRender}
          {...props}
          {...settings}
          {...orgStructure}
        >
          {children}
        </ProLayout>
      )}
    </VisualizerProvider>
  );
};

export default connect(({ token, orgStructure, global, settings, Permissions, configMenus }) => ({
  token,
  orgStructure,
  collapsed: global.collapsed,
  configMenus: global.configMenus,
  settings,
  Permissions,
}))(BasicLayout);
